<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图片名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入图片文件名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" prop="uploadTime">
        <el-date-picker clearable
          v-model="queryParams.uploadTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择图片上传时间">
        </el-date-picker>
      </el-form-item>
      
      <el-form-item label="是否公开" prop="privacySetting">
        <el-input
          v-model="queryParams.privacySetting"
          placeholder="请输入图片隐私"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="逻辑删除" prop="isDeleted">
        <el-input
          v-model="queryParams.isDeleted"
          placeholder="请输入逻辑删除标志"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['blog:images:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['blog:images:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['blog:images:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['blog:images:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="imagesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="80" />
      <el-table-column label="图片名" align="center" prop="fileName" />
      <el-table-column label="路径" align="center" prop="url" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.url" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传用户ID" align="center" prop="userId" />
      <el-table-column label="标签" align="center" prop="tagIds" >
        <template #default="scope">
          <div v-for="tag in tagsImgList" :key="tag.id" >
            <el-tag type="success" style="margin-right: 10px;" v-if="scope.row.tagIds && scope.row.tagIds.includes(tag.id)">{{tag.tagName}}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否公开" align="center" prop="privacySetting" >
        <template #default="scope">
          <el-tag>{{ scope.row.privacySetting === 0 ? "是" : "否" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  width="200px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="info"  @click="handleInfo(scope.row)" v-hasPermi="['blog:images:list']">查看详情</el-button>
          <el-button link type="info" @click="handleUpdate(scope.row)" v-hasPermi="['blog:images:edit']">修改</el-button>
          <el-button link type="info"  @click="handleDelete(scope.row)" v-hasPermi="['blog:images:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改图片对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="imagesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="fileName">
          <el-input v-model="form.fileName"  @input="form.fileName = form.fileName.trim()"  placeholder="请输入图片文件名" />
        </el-form-item>
         <el-form-item label="标签" prop="tagIds">
           <el-select v-model="form.tagIds"  
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="2"
              style="width: 150px" 
              placeholder="标签">
            <el-option
              v-for="item in tagsImgList"
              :key="item.id"
              :label="item.tagName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片路径" prop="url">
          <image-upload v-model="form.url"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


        <!-- 详情对话框 -->
    <el-dialog :title="title" v-model="detailOpen"  append-to-body>
      <el-form :model="imagesInfo" label-width="100px">
        <el-form-item label="文件名">
          {{imagesInfo.fileName}}
        </el-form-item>
        <el-form-item label="标签">
          <div v-for="tag in tagsImgList" :key="tag.id" >
            <el-tag type="success" style="margin-right: 10px;" v-if="imagesInfo.tagIds && imagesInfo.tagIds.includes(tag.id)">{{tag.tagName}}</el-tag>
          </div>
        </el-form-item>
        <el-form-item label="上传时间">
          {{ imagesInfo.uploadTime }}
        </el-form-item>

        <el-form-item label="上传用户">
          {{ imagesInfo.userId }}
        </el-form-item>
        <el-form-item label="是否公开">
          <el-tag>{{ imagesInfo.privacySetting === 0 ? "是" : "否" }}</el-tag>
        </el-form-item>
        <el-form-item label="存储路径">
          <span @click="copyText(imagesInfo.url)" style="cursor: pointer; color: #409EFF;">{{ imagesInfo.url }}</span>
        </el-form-item>
        <el-form-item label="图片描述">
          {{ imagesInfo.description === null ? "无" : imagesInfo.description }}
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Images">
import { listImages, getImages, delImages, addImages, updateImages } from "@/api/blog/images";
import { listTagsImg } from "../../../api/blog/tagsImg";
import { loadAllParams } from "../../../api/params";

const { proxy } = getCurrentInstance();

const imagesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileName: null,
    uploadTime: null,
    description: null,
    userId: null,
    privacySetting: null,
    isDeleted: null,
  },
  rules: {
    fileName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    url: [
      { required: true, message: "图片路径不能为空", trigger: "blur" }
    ],
    tagIds: [
      { required: true, message: "请选择标签", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询图片列表 */
function getList() {
  loading.value = true;
  getTagsImg();
  listImages(queryParams.value).then(response => {
    imagesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    fileName: null,
    url: null,
    uploadTime: null,
    description: null,
    userId: null,
    privacySetting: null,
    isDeleted: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("imagesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 获取标签列表 */
const tagsImgList = ref([]);
function getTagsImg(){
  listTagsImg(loadAllParams).then(response => {
    tagsImgList.value  = response.rows;
  });
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTagsImg();
  open.value = true;
  title.value = "添加图片";
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTagsImg();
  getImages(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改图片";
  });
  
}

/**查看详情 */
const imagesInfo = ref({});
const detailOpen = ref(false);
function handleInfo(row){
  reset();
  getTagsImg();
  const _id = row.id 
  getImages(_id).then(response => {
    imagesInfo.value = response.data;
    detailOpen.value = true;
    title.value = "查看详情";
  });
}

//是否重复
function isImageNameDuplicate(fileName) {
 
  return imagesList.value.some(item => item.fileName === fileName);
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["imagesRef"].validate(valid => {
    if( form.value.id === null && isImageNameDuplicate(form.value.fileName)){
      proxy.$modal.msgError("图片名称已存在，请更换名称！");
    }else{
     if (valid ) {
      if (form.value.id != null) {
        updateImages(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addImages(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
    }

  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除图片编号为"' + _ids + '"的数据项？').then(function() {
    return delImages(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('blog/images/export', {
    ...queryParams.value
  }, `images_${new Date().getTime()}.xlsx`)
}

//  单击复制文本
async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess("复制成功");
  } catch (err) {
    proxy.$modal.msgError("复制失败，请重试");
  }
}

getList();
</script>
